package mongo

import (
	"context"
	"gogo/log"
	"sync"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var (
	mp_db_mongo *Mongo_Class
)

func This() *Mongo_Class {
	if mp_db_mongo == nil {
		mp_db_mongo = &Mongo_Class{}
	}
	return mp_db_mongo
}

type Mongo_Class struct {
	mMutex sync.Mutex
	//mPwg        sync.WaitGroup
	mpMGClient *mongo.Client
	//mProcess    int
	//mMaxProcess int
}

func (c *Mongo_Class) EndWorking() {
	//c.mPwg.Wait()
}

func (c *Mongo_Class) Init(max int, opts ...*options.ClientOptions) {
	c.mMutex.Lock()
	defer c.mMutex.Unlock()

	if c.mpMGClient != nil {
		return
	}

	//c.mMaxProcess = max

	log.This().Debug("连接MongoDB ...")

	var err error
	for {
		c.mpMGClient, err = mongo.Connect(context.TODO(), opts...)

		if c.mpMGClient != nil && err == nil {
			if err = c.mpMGClient.Ping(context.TODO(), nil); err == nil {
				log.This().Debug("连接MongoDB成功")
				return
			}
		}
		log.This().ErrorF("MongoDB连接失败: %v", err)
		time.Sleep(time.Second)
	}
}

func (c *Mongo_Class) GetMGClient() *mongo.Client {
	return c.mpMGClient
}
